package cn.iocoder.yudao.module.promotion.service.rankingrecord;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.promotion.controller.admin.rankingrecord.vo.RankingRecordPageReqVO;
import cn.iocoder.yudao.module.promotion.controller.admin.rankingrecord.vo.RankingRecordSaveReqVO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.rankingrecord.RankingRecordDO;
import cn.iocoder.yudao.module.promotion.dal.mysql.rankingrecord.RankingRecordMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.RANKING_RECORD_NOT_EXISTS;

/**
 * 排行榜分佣记录 Service 实现类
 *
 * @author 万民匠心
 */
@Service
@Validated
public class RankingRecordServiceImpl implements RankingRecordService {

    @Resource
    private RankingRecordMapper rankingRecordMapper;

    @Override
    public Long createRankingRecord(RankingRecordSaveReqVO createReqVO) {
        // 插入
        RankingRecordDO rankingRecord = BeanUtils.toBean(createReqVO, RankingRecordDO.class);
        rankingRecordMapper.insert(rankingRecord);
        // 返回
        return rankingRecord.getId();
    }

    @Override
    public void updateRankingRecord(RankingRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateRankingRecordExists(updateReqVO.getId());
        // 更新
        RankingRecordDO updateObj = BeanUtils.toBean(updateReqVO, RankingRecordDO.class);
        rankingRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteRankingRecord(Long id) {
        // 校验存在
        validateRankingRecordExists(id);
        // 删除
        rankingRecordMapper.deleteById(id);
    }

    private void validateRankingRecordExists(Long id) {
        if (rankingRecordMapper.selectById(id) == null) {
            throw exception(RANKING_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public RankingRecordDO getRankingRecord(Long id) {
        return rankingRecordMapper.selectById(id);
    }

    @Override
    public PageResult<RankingRecordDO> getRankingRecordPage(RankingRecordPageReqVO pageReqVO) {
        return rankingRecordMapper.selectPage(pageReqVO);
    }

    @Override
    public List<RankingRecordDO> getRankingRecordList(Long rankingId) {
        if (rankingId == null) {
            return Lists.newArrayList();
        }
        return rankingRecordMapper.selectList(new LambdaQueryWrapperX<RankingRecordDO>()
                .eqIfPresent(RankingRecordDO::getRankingId, rankingId)
                .orderByDesc(RankingRecordDO::getScore));
    }

}